package testProject;

import java.io.IOException;
import java.io.StringReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.onpositive.page.pagerendering.SiteContentRenderer;
import com.onpositive.page.pagerendering.UserProfilePageRenderer;
import com.onpositive.page.pagerendering.interfaces.ISiteContentRenderer;
import com.onpositive.storage.managers.AccountManager;
import com.onpositive.storage.managers.ProfilesUsersManager;

public class UserProfileManagingServlet extends HttpServlet {

	private static SiteContentRenderer iscr = (SiteContentRenderer) SiteContentRenderer
			.getSiteContentRenderer();
	
	private static final String MESSAGE_ID = "message";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String nickName = AccountManager.getCurrentUserNickName();
		UserProfilePageRenderer uppr = new UserProfilePageRenderer();
		String message = "These parameters are used for update site accessing";
		Object attr = req.getSession().getAttribute(MESSAGE_ID);
		if( attr != null){
			message = (String) attr;
			req.getSession().removeAttribute(MESSAGE_ID);
		}
		iscr.initRenderer(getServletContext());
		iscr.render(resp, new StringReader((uppr.getContent(nickName, message))), "profile.page", false);
				
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String nickName = AccountManager.getCurrentUserNickName();
		Map<String, Object> params = new HashMap<String, Object>();
		for(Enumeration e = req.getParameterNames(); e.hasMoreElements();){
			String p = (String)e.nextElement();
			Object val = req.getParameter(p);
			params.put(p,val);
		}
		ProfilesUsersManager.safeUserProperties(nickName,params);		
		HttpSession s = req.getSession();
		s.setAttribute(MESSAGE_ID,"Parameters saved successfull.");
		resp.sendRedirect("/profile.page");
	}
}
